package com.powernode.service.impl;
import com.alibaba.fastjson.JSON;
import com.powernode.domain.Category;
import com.powernode.domain.Product;
import com.powernode.domain.ProductImg;
import com.powernode.mapper.CategoryMapper;
import com.powernode.mapper.ProductImgMapper;
import com.powernode.mapper.ProductMapper;
import com.powernode.service.CategoryService;
import com.powernode.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class CategoryServiceImpl implements CategoryService{

    /**
     * 类别表
     */
    @Autowired
    private CategoryMapper categoryMapper;

    /**
     * 商品表
     */
    @Autowired
    private ProductMapper productMapper;

    /**
     * 商品图片表
     */
    @Autowired
    private ProductImgMapper productImgMapper;

    /**
     * 查询商品分类
     * @return
     */
    @Override
    public List<Category> selectByList() {
        //查询全部分类
        List<Category> list = categoryMapper.selectByList();
        //转树形
        //2.转树形
        List<Category> treeMenus = transTreeMenu(list, 0L);
        //进行json格式转换
        String menuTree = JSON.toJSONString(treeMenus);
        return treeMenus;
    }

    /**
     * 查询类别推荐商品
     * @return
     */
    public List<Category> selectByListFirst(){
        //查询全部分类
        List<Category> list = categoryMapper.selectByListFirst();

        if (list.size()==0){
            return list;
        }
        //根据一级分类查询对应推荐
        list.forEach(category -> {
            Integer categoryId = category.getCategoryId();
           List<Product> products = productMapper.selectProductByCategoryId(categoryId);
            //查询图片集合
            products.forEach(product -> {
                int i = Integer.parseInt(product.getProductId());
                List<ProductImg> ImgList =productImgMapper.selectImgByProductId(i);
                product.setImgs(ImgList);
            });
           category.setProducts(products);
        });

        return list;
    }



    /**
     * 转树形结构
     * @param sysMenus
     * @param pid
     * @return
     */
    private List<Category> transTreeMenu(List<Category> sysMenus, long pid) {

        List<Category> sysMenusFather = new ArrayList<>();
        sysMenus.forEach(sysMenu -> {
            if (sysMenu.getParentId()==pid) {
                sysMenu.setList(transTreeMenu(sysMenus, sysMenu.getCategoryId()));
                sysMenusFather.add(sysMenu);
            }
        });
        return sysMenusFather;
    }
}
